<template>
  <view class="viewport">
    <wd-navbar
      :bordered="false"
      placeholder
      safeAreaInsetTop
      left-arrow
      custom-style="background-color:#92beab;"
      custom-class="color:#fff"
    >
      <template #title>
        <view class="custom-title-style">新建搭建</view>
      </template>
      <template #capsule>
        <wd-navbar-capsule @back="handleBack" @back-home="handleBackHome" />
      </template>
    </wd-navbar>
    <view class="create-match-container">
      <!-- 标题 -->
      <view class="header">
        <text class="title">新建搭配</text>
      </view>

      <!-- 表单 -->
      <view class="form">
        <!-- 搭配名称 -->
        <view class="form-item">
          <text class="label">
            <text>搭配名称</text>
            <text class="required-star">*</text>
          </text>
          <input
            type="text"
            v-model="form.name"
            placeholder="请输入搭配名称"
            class="input"
          />
        </view>

        <!-- 搭配描述 -->
        <view class="form-item">
          <text class="label">搭配描述</text>
          <textarea
            v-model="form.description"
            placeholder="请输入搭配描述"
            class="textarea"
          ></textarea>
        </view>
        <view class="form-item">
          <text class="label">搭配图片</text>
          <view class="image-list">
            <view
              class="image-item"
              v-for="(img, index) in form.images"
              :key="index"
            >
              <image :src="img" mode="aspectFill" class="image" />
              <view class="delete-btn" @click="removeImage(index)">×</view>
            </view>
            <view class="upload-btn" @click="chooseImage">
              <uni-icons type="plus" size="28" color="#92beab"></uni-icons>
            </view>
          </view>
        </view>

        <!-- 标签选择 -->
        <view class="tag-list">
          <text
            v-for="tag in allTags"
            :key="tag"
            :class="['tag', form.tags.includes(tag) ? 'active' : '']"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </text>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="save-btn" @click="saveMatch"> 保存搭配 </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { getTags, postMatch } from "@/api/match";
import { onLoad } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";

const form = reactive({
  name: "",
  description: "",
  images: [] as string[],
  tags: [] as string[],
});

const allTags = ref<string[]>([]);
// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 6, // 最多选择 6 张
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      if (Array.isArray(res.tempFilePaths)) {
        res.tempFilePaths.forEach((p: string, i: number) => console.log(i, p));
        const newImages = [...form.images, ...res.tempFilePaths].slice(0, 6);
        form.images = newImages;
      } else if (typeof res.tempFilePaths === "string") {
        const newImages = [...form.images, res.tempFilePaths].slice(0, 6);
        form.images = newImages;
      }
    },
    fail: (err) => {
      console.error("选择图片失败:", err);
    },
  });
};

// 删除图片
const removeImage = (index: number) => {
  form.images.splice(index, 1);
};

// 切换标签选中
const toggleTag = (tag: string) => {
  const idx = form.tags.indexOf(tag);
  if (idx > -1) {
    form.tags.splice(idx, 1);
  } else {
    form.tags.push(tag);
  }
};

// 保存搭配
const saveMatch = async () => {
  if (!form.name.trim()) {
    uni.showToast({ title: "请输入搭配名称", icon: "none" });
    return;
  }
  if (form.images.length === 0) {
    uni.showToast({ title: "请至少上传一张图片", icon: "none" });
    return;
  }

  const uploadPromises = form.images.map((filePath) => {
    return uni.uploadFile({
      url: "/match/uploadImages",
      filePath,
      name: "files",
      method: "POST",
    });
  });
  const resArr = await Promise.all(uploadPromises);
  const idImage: any = [];
  resArr.forEach(async (res) => {
    const data = JSON.parse(res.data);
    if (data.code === 200 || data.code === "200") {
      idImage.push(...data.data);
    } else {
      console.warn("上传失败", data.msg);
    }
  });
  if (idImage.length === form.images.length) {
    const params = {
      name: form.name,
      description: form.description,
      images: idImage,
      tags: form.tags,
    };
    await postMatch(params);
  }

  // 后续改成调用后端 API
  uni.showToast({ title: "保存成功", icon: "success" });
  setTimeout(() => {
    uni.navigateBack();
  }, 1000);
};

// 获取标签列表
const gettags = async () => {
  const res: any = await getTags();
  if (res.code === "200" && Array.isArray(res.data)) {
    // 只取 name
    allTags.value = res.data.map((tag: any) => tag.name);
  }
};
const handleBack = () => {
  uni.navigateBack({});
};
const handleBackHome = () => {
  uni.reLaunch({
    url: "/pages/index/index",
  });
};
onLoad(() => {
  gettags();
});
</script>

<style scoped lang="scss">
.create-match-container {
  padding: 20rpx;
  background: #f8f8f8;
  min-height: 100%;
}

.header {
  margin-bottom: 30rpx;
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form-item {
  margin: 0 20rpx;
  margin-bottom: 24rpx;
  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: flex;
  }
  .input,
  .textarea {
    display: flex;
    width: 100%;
    background: #fff;
    border-radius: 8rpx;
    border: 1rpx solid #ddd;
    // padding: 16rpx;
    font-size: 28rpx;
  }
  .textarea {
    min-height: 120rpx;
  }
  .input {
    height: 60rpx;
  }
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;

  .image-item {
    position: relative;
    .image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
    }
    .delete-btn {
      position: absolute;
      top: -12rpx;
      right: -12rpx;
      background: rgba(0, 0, 0, 0.6);
      color: #fff;
      border-radius: 50%;
      width: 36rpx;
      height: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
    }
  }

  .upload-btn {
    width: 160rpx;
    height: 160rpx;
    background: #fff;
    border: 2rpx dashed #92beab;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;

  .tag {
    padding: 8rpx 20rpx;
    background: #f0f8f5;
    border-radius: 20rpx;
    color: #92beab;
    font-size: 24rpx;
  }
  .tag.active {
    background: #92beab;
    color: #fff;
  }
}

.save-btn {
  margin-top: 40rpx;
  background: #92beab;
  color: #fff;
  text-align: center;
  padding: 20rpx;
  border-radius: 8rpx;
  font-size: 30rpx;
}
.required-star {
  color: #e74c3c;
  font-size: 28rpx;
  margin-left: 8rpx;
  line-height: 1;
  font-weight: bold;
  // 可选：让星号稍微上移一点
  position: relative;
}
</style>
